<?php

class User {

  /**
   * current viewer
   * @var user
   */
  protected static $_viewer;
  /**
   * user id
   * @var int
   */
  protected $_id = 0;
  /**
   * user data
   * @var array
   */
  protected $_data = array();

  /**
   *
   * @param int $id [optional]
   */
  public function __construct($id = 0) {
    $this->_id = $id;
    if ($id) {
      $this->_setup();
    }
  }

  protected function _setup() {
    $table = db::get_tablename('user');
    if ($row = db::factory()->fetchRow("select * from $table where id=?", $this->_id)) {
      $this->_data = $row;
    } else if ($this->_id) {
      $_SESSION['user_id'] = 0;
      auth::clean($this->_id);
    }
  }

  /**
   * get user profile
   * return profile
   */
  public function get_profile() {
    
  }

  /**
   * get user membership
   * @return membership
   */
  public function get_membership() {
    
  }

  /**
   * true if current user is logged
   * @return bool
   */
  public function is_logged() {
    if ($this->_id) {
      return true;
    }
    return false;
  }

  /**
   * set current user is loged in
   * @param int $id
   */
  public function login($id) {
    $_SESSION['uid'] = $id;
  }

  /**
   * set current user is loged out
   */
  public function logout() {
    $_SESSION['uid'] = 0;
  }

  /**
   *
   * @return string
   */
  public function get_username() {
    return @$this->_data['username'];
  }

  /**
   * @return string
   */
  public function get_fullname() {
    return @$this->_data['firstname'] . ' ' . @$this->_data['lastname'];
  }

  /**
   *
   * @return string
   */
  public function get_shortname() {
    return @$this->_data['firstname'];
  }

  /**
   *
   * @return string
   */
  public function get_firstname() {
    return @$this->_data['firstname'];
  }

  /**
   *
   * @return string
   */
  public function get_lastname() {
    return @$this->_data['lastname'];
  }

  /**
   * @return string
   */
  public function get_email() {
    return @$this->_data['email'];
  }

  /**
   * @return string
   */
  public function getRole() {
    return @$this->_data['role'] ? $this->_data['role'] : 'guest';
  }

  /**
   * get current user
   * @return user
   */
  public static function current() {

    if (self::$_viewer == NULL) {
      session::start();
      $user_id = auth::get_current_id();
      self::$_viewer = new self($user_id);
    }
    return self::$_viewer;
  }

  /**
   * return true if current user have permission to subject
   * @param string $subject
   * @return bool
   * @throws Exception
   */
  public static function hasPermission($subject) {
    if ($role == 'admin') {
      return true;
    }
    
    $sql = "select role,type from acl_permission where subject =:subject";
    $result = Db::factory()->fetchPairs($sql, array('subject' => $subject));
    if ($result) {
      return true;
    }
    throw new Exception('Permission deny');
  }

}